package com.bwie.lib_core.network.interceptor;

import android.util.Log;
import com.bwie.lib_core.util.MD5SignUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Iterator;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * 自定义Sign拦截器
 * */
public class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //好处:通过拦截器自动在请求参数中添加sign签名;
        //不需要每次网络请求中在调用签名生成工具类进行签名
        //以及添加到网络请求参数中去
        //获取服务器请求的json参数拼接为一个新的string字符串
        //拼接完成后->使用MD5Utils工具类进行MD5加密为sign签名
        //再次添加到请求参数中->发起网络请求
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        builder.url(request.url());
        //原有的请求的头部分添加进来
        builder.headers(request.headers());
        RequestBody body = request.body();
        Buffer buf = new Buffer();
        body.writeTo(buf);
        String bodyStr = buf.toString();//请求体中的json字符串
        buf.close();
        //[text={"uName":"zxy","uPwd":"123456","time":"1582342403"}]
        //String字符串提取操作->提取出字符串中json
        bodyStr = bodyStr.substring(bodyStr.indexOf("{"),bodyStr.lastIndexOf("}")+1);
        Log.e("ZXY","SignInterceptor请求值:"+bodyStr);
        StringBuffer buffer = new StringBuffer();
        JSONObject object = null;
        //sign请求体重的jsonobject中所有key对应的value拼接成一个String字符串+tamboo
        //进行md5加密
        try {
            object = new JSONObject(bodyStr);
            //jsonobject中的key转化为迭代器
            Iterator<String> it = object.keys();
            //遍历迭代器中的jsonobject下的key->根据key获取value
            while (it.hasNext()){
                buffer.append(object.getString(it.next()));
            }
            //拼接完成转化为string->md5加密后的string字符串
            String md5Str = MD5SignUtil.buildSign(buffer.toString());
            //在原始数据的基础上添加sign
            object.put("sign",md5Str);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //打印拼接完sign的参数数据->人工校验
        Log.e("ZXY","SignInterceptor:校验请求参数:"+object.toString());
        //重新构建requestbody
        if (object!=null) {
            body = RequestBody.create(MediaType.parse("application/json"), object.toString());
            //再次生成的body添加到builder中进行构建
            builder.post(body);//将二次构建完成的requestbody添加到request建造者中
            request = builder.build();//使用requestbuilder建造者建造request请求
        }
        return chain.proceed(request);
    }
}
